package com.study8.demo8.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;

@Controller
class FileUploadController {

  @Value("${filePath}")
  private String filePath;

  @GetMapping("/upload")
  public String uploading() {
    //跳转到 templates 目录下的 uploading.html
    return "uploading";
  }

  //处理文件上传
  @PostMapping("/uploading")
  @ResponseBody
  public String uploading(@RequestParam("file") MultipartFile file,
                   HttpServletRequest request) throws Exception {
    uploadFile(file.getBytes(), filePath, file.getOriginalFilename());
    System.out.println("文件上传成功!");
    return "uploading success";
  }



  public void  uploadFile(byte[] file, String filePath, String fileName) throws Exception {
    File targetFile = new File(filePath);
    if(!targetFile.exists()){
      targetFile.mkdirs();
    }
    FileOutputStream out = new FileOutputStream(filePath+fileName);
    out.write(file);
    out.flush();
    out.close();
  }

}

